package io.renren.modules.sys.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import io.renren.common.utils.Result;
import io.renren.modules.sys.dto.QQuestionsDTO;
import io.renren.modules.sys.entity.QAnswerer;
import io.renren.modules.sys.entity.QQuestion;
import io.renren.modules.sys.service.QAnswererService;
import jakarta.annotation.Resource;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * (QAnswerer)表控制层
 *
 * @author makejava
 * @since 2024-07-03 16:24:19
 */
@RestController
@RequestMapping("qAnswerer")
public class QAnswererController {
    /**
     * 服务对象
     */
    @Resource
    private QAnswererService qAnswererService;

    /**
     * 分页查询
     *
     * @param qAnswerer 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<QAnswerer>> queryByPage(QAnswerer qAnswerer, PageRequest pageRequest) {
        return ResponseEntity.ok(this.qAnswererService.queryByPage(qAnswerer, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<QAnswerer> queryById(@PathVariable("id") String id) {
        return ResponseEntity.ok(this.qAnswererService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param qAnswerer 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<QAnswerer> add(QAnswerer qAnswerer) {
        return ResponseEntity.ok(this.qAnswererService.insert(qAnswerer));
    }

    /**
     * 编辑数据
     *
     * @param qAnswerer 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<QAnswerer> edit(QAnswerer qAnswerer) {
        return ResponseEntity.ok(this.qAnswererService.update(qAnswerer));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(String id) {
        return ResponseEntity.ok(this.qAnswererService.deleteById(id));
    }

    @GetMapping("/getQuestionsByAnswererId")
    @RequiresPermissions("sys:user:info")
    public Result<QQuestionsDTO> getQuestionsByAnswererId(String id){
        QQuestionsDTO result = new QQuestionsDTO();
        result.setAnswererId(id);
        result.setInvestigationId(this.qAnswererService.queryById(id).getInvestigationId());

        List<QQuestion> questions = new ArrayList<>();
        try {
            questions = this.qAnswererService.getQuestionsByAnswerersId(id);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        result.setQuestions(questions);
        return new Result<QQuestionsDTO>().ok(result);
    }
}

